<template>
  <view class="address-list">
    <view class="header">
      <text class="title">地址列表</text>
    </view>
    
    <!-- 地址列表 -->
    <view class="address-item" v-for="(address, index) in addresses" :key="index" @click="selectAddress(address)">
      <view class="address-info">
        <view class="name-line">
          <text class="name">{{address.name}}</text>
          <text class="phone">{{address.phone}}</text>
          <text v-if="address.isDefault" class="default-tag">默认</text>
        </view>
        <text class="address-detail">{{address.city}} {{address.department}} {{address.houseNumber}}</text>
      </view>
      <view class="operation">
        <text @click.stop="editAddress(address)" class="edit">编辑</text>
        <text @click.stop="deleteAddress(address)" class="delete">删除</text>
      </view>
    </view>
    
    <!-- 新增地址按钮 -->
    <view class="add-btn-container">
      <button class="add-btn" @click="navigateToAddAddress">
        <uni-icons type="plusempty" size="16" color="#fff"></uni-icons>
        新增地址
      </button>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      addresses: [],
      userId: ''
    };
  },
  onLoad() {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id;
    }
    this.fetchAddresses();
  },
  methods: {
    async fetchAddresses() {
      try {
        const response = await uni.request({
          url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users/${this.userId}`,
          method: 'GET'
        });
        if (response.statusCode === 200) {
          const user = response.data;
          this.addresses = user.addresses || [];
        } else {
          uni.showToast({
            title: '获取地址列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '获取地址列表失败，请重试',
          icon: 'none'
        });
      }
    },
    editAddress(address) {
      const encodedAddress = encodeURIComponent(JSON.stringify(address));
      uni.navigateTo({
        url: `/pages/me/address-edit?address=${encodedAddress}`
      });
    },
    deleteAddress(address) {
      uni.showModal({
        title: '确认删除',
        content: '你确定要删除该地址吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await uni.request({
                url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users/${this.userId}`,
                method: 'GET'
              });
              if (response.statusCode === 200) {
                const user = response.data;
                const updatedAddresses = user.addresses.filter(addr => addr.id !== address.id);
                const updateResponse = await uni.request({
                  url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users/${this.userId}`,
                  method: 'PUT',
                  data: {
                    ...user,
                    addresses: updatedAddresses
                  }
                });
                if (updateResponse.statusCode === 200) {
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                  });
                  this.fetchAddresses();
                } else {
                  uni.showToast({
                    title: '删除失败',
                    icon: 'none'
                  });
                }
              } else {
                uni.showToast({
                  title: '获取用户信息失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              uni.showToast({
                title: error.message || '删除失败，请重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    navigateToAddAddress() {
      uni.navigateTo({
        url: '/pages/me/address-edit'
      });
    },
selectAddress(address) {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const prevPage = pages[pages.length - 2];
    
    // 检查是否从确认订单页面跳转过来
    if (currentPage.options.from === 'confirm') {
      uni.setStorageSync('selectedAddress', address);
      uni.navigateBack();
      return;
    }
    
    // 原有逻辑
    const encodedAddress = encodeURIComponent(JSON.stringify(address));
    uni.navigateTo({
      url: `/pages/must/must?address=${encodedAddress}`
    });
  }
  }
};
</script>

<style scoped>
.address-list {
  min-height: 100vh;
  background-color: #f7f7f7;
  padding-bottom: 40rpx;
}

.address-list .header {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.address-list .header .title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
}

.address-list .address-item {
  background-color: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.address-list .address-item:active {
  background-color: #f9f9f9;
}

/* 默认地址标识 */
.address-list .address-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6rpx;
  background-color: #0099FF;
  display: var(--default-display, none);
}

.address-list .address-item.is-default::before {
  --default-display: block;
}

.address-info .name-line {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.address-info .name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-right: 20rpx;
}

.address-info .phone {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.address-info .default-tag {
  font-size: 24rpx;
  color: #0099FF;
  background-color: #e6f7ff;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.address-info .address-detail {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.operation {
  display: flex;
  justify-content: flex-end;
  margin-top: 24rpx;
  padding-top: 16rpx;
  border-top: 1rpx dashed #eee;
}

.operation .edit,
.operation .delete {
  font-size: 28rpx;
  padding: 8rpx 16rpx;
}

.operation .edit {
  color: #0099FF;
  margin-right: 20rpx;
}

.operation .delete {
  color: #FF4D4F;
}

.add-btn-container {
  padding: 0 30rpx;
  margin-top: 20rpx;
}

.add-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #0099FF;
  color: #fff;
  font-size: 32rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn:active {
  opacity: 0.9;
}

.add-btn .uni-icons {
  margin-right: 10rpx;
}
</style>